package com.inspur.xiaoju.controller;

import com.inspur.xiaoju.common.ApiResponse;
import com.inspur.xiaoju.dto.CreateSurveyDto;
import com.inspur.xiaoju.model.Survey;
import com.inspur.xiaoju.service.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;  // 添加这个导入
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/surveys")
public class SurveyController {

    @Autowired
    private SurveyService surveyService;
    
    @PostMapping
    public ApiResponse<Map<String, String>> create(@Valid @RequestBody CreateSurveyDto createDto,
                                                  @RequestAttribute("userId") String userId,
                                                  @RequestAttribute("username") String username) {
        Survey survey = surveyService.create(createDto, userId, username);
        // 替换 Map.of() 为 HashMap
        Map<String, String> result = new HashMap<>();
        result.put("id", survey.getId());
        return ApiResponse.success(result);
    }
    
    @GetMapping("/{id}")
    public ApiResponse<Survey> findById(@PathVariable String id) {
        return ApiResponse.success(surveyService.findById(id));
    }
    
    @GetMapping("/path/{surveyPath}")
    public ApiResponse<Survey> findBySurveyPath(@PathVariable String surveyPath) {
        return ApiResponse.success(surveyService.findBySurveyPath(surveyPath));
    }
    
    @GetMapping("/workspace/{workspaceId}")
    public ApiResponse<List<Survey>> findByWorkspaceId(@PathVariable String workspaceId) {
        return ApiResponse.success(surveyService.findByWorkspaceId(workspaceId));
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Survey> update(@PathVariable String id, @RequestBody Map<String, Object> updates) {
        return ApiResponse.success(surveyService.update(id, updates));
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable String id) {
        surveyService.delete(id);
        return ApiResponse.success(null);
    }
    
    @PutMapping("/{id}/status")
    public ApiResponse<Survey> updateStatus(@PathVariable String id, @RequestBody Map<String, String> body) {
        String status = body.get("status");
        return ApiResponse.success(surveyService.updateStatus(id, status));
    }
}